import { useEffect, useState } from 'react'
import s from './index.module.scss'

type MenuType = 'danger' | 'new' | 'hard' | 'import' | ''

export type MenuItem = {
  key: string,
  type?: 'section' | 'menu',
  label: string,
  tagType?: MenuType,
  icon?: string,
  onSelected?: () => any,
  [key: string]: any
}

interface MenuProps {
  menus: Array<MenuItem>,
  onClick?: (item: MenuItem) => any,
  defaultKey?: string
}

export default function Menu(props: MenuProps) {
  const {menus, onClick, defaultKey} = props
  const [selectedKey, setSelectedKey] = useState(defaultKey || '')

  function onClickHandler(menu: MenuItem) {
    setSelectedKey(menu.key)
    onClick && onClick(menu)
  }

  function getMenuItem(menu: MenuItem) {
    if (menu.type == 'section') {
      return (
        <div className={s.section} key={menu.key}>
          <div className={s.name}>{menu.label}</div>
        </div>
      )
    }

    if (menu.type == 'menu') {
      return (
        <button 
          onClick={() => onClickHandler(menu)}
          key={menu.key} 
          className={(selectedKey == menu.key) ? `${s.button} ${s.active}` : s.button}
        >
          {menu.label}
        </button>
      )
    }
  }

  return (
    <div className={s.container}>
      {menus.map((menu) => (
        getMenuItem(menu)
      ))}
    </div>
  )
}
